package cn.nawang.ebeim.ui.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.nawang.ebeim.ui.bean.User;


public class UserLoginWebInterceptor implements HandlerInterceptor {
  private static final Logger LOG = LoggerFactory.getLogger(UserLoginWebInterceptor.class);

  public String[] allowUrls;// 还没发现可以直接配置不拦截的资源，所以在代码里面来排除

  public void setAllowUrls(String[] allowUrls) {
    this.allowUrls = allowUrls;
  }

  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
  }

  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modeView) throws Exception {

  }

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    try {
      String path = request.getContextPath(); 
      String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; 
      String requestUrl = request.getRequestURI().replace(path, "");
      if (null != allowUrls && allowUrls.length >= 1) for (String url : allowUrls) {
        if (requestUrl.contains(url)) {
          return true;
        }
      }
      // 测试时默认使用——用户名为benchi1的用户登录
      User loginUser = (User) request.getSession().getAttribute("user");
      if (loginUser == null) {
        LOG.info("user is null.............");
//        request.getRequestDispatcher("dispatcher/login").forward(request, response);
        response.setHeader("Cache-Control", "no-store");  
        response.setDateHeader("Expires", 0);  
        response.setHeader("Prama", "no-cache");  
        response.sendRedirect(basePath+"/web/html/login.html"); 
        return false;
      }
      return true;
    } catch (Throwable e) {
      // 返回服务端处理错误指令
      return false;
    }
  }
}

